<script setup>

import { reactive} from 'vue';

    // let items = reactive([
    //     {
    //         id:"item1",
    //         name:"可口可乐"
    //     },
    //     {
    //         id:"item2",
    //         name:"薯片"
    //     },
    //     {
    //         id:"item3",
    //         name:"炸鸡"
    //     },
    //     {
    //         id:"item4",
    //         name:"小电影"
    //     }
    // ]);

    let shoppingCart = reactive([
        {
            name:"switch",
            price:2000,
            number:1
        },
        {
            name:"野炊",
            price:350,
            number:1
        },
        {
            name:"可乐",
            price:3.5,
            number:12
        },
        {
            name:"内存条",
            price:234.99,
            number:2
        },
        {
            name:"固态硬盘",
            price:390,
            number:1
        },
        {
            name:"鼠标",
            price:175,
            number:1
        }
    ]);

    function accumulateShoppingCart() {
        let sum = 0;
        for (let index = 0; index < shoppingCart.length; ++index) {
            let per = shoppingCart[index].price * shoppingCart[index].number;
            sum += per;
        }

        return sum;
    }

    function removeItemFromShoppingCart(index) {
        shoppingCart.splice(index, 1);
    }

    function clearShoppingCart() {
        shoppingCart.splice(0);
    }

</script>

<template>
    <div>
        <h1>您的购物车如下</h1> <br>
        <table border="1px">
            <thead>
                <tr>
                    <th>序号</th>
                    <th>名称</th>
                    <th>单价</th>
                    <th>数量</th>
                    <th>小计</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody v-if="shoppingCart.length > 0">
                <tr v-for="(item, index) in shoppingCart" :key="index">
                    <td>{{ index + 1 }}</td>
                    <td>{{ item.name }}</td>
                    <td>{{ item.price }}</td>
                    <td>{{ item.number }}</td>
                    <td>{{ item.price * item.number }}</td>
                    <td>
                        <button @click="removeItemFromShoppingCart(index)">删除</button>
                    </td>
                </tr>
            </tbody>
            <tbody v-else>
                <tr>
                    <td colspan="6">没有商品 请去选购一些吧</td>
                </tr>
            </tbody>
        </table>
        购物车总金额为: <B>{{ accumulateShoppingCart() }}</B>元 <br>
        <button @click="clearShoppingCart()">一键清空购物车</button>
    </div>


    <!-- <div>
        <ul>
            我需要: <br>
            <li v-for="(item, index) in items" v-bind:key="item.id">
                {{ index + 1 }}.{{ item.name }}
            </li>
        </ul>
    </div> -->
</template>

<style scoped>
</style>
